package com.example.weatherapp1.service


import android.app.Service
import android.content.Intent
import android.os.IBinder
import androidx.lifecycle.LifecycleService
import androidx.lifecycle.lifecycleScope
import com.example.weatherapp1.data.repository.WeatherRepository
import com.example.weatherapp1.domain.service.WeatherService
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import javax.inject.Inject


@AndroidEntryPoint
class WeatherUpdateService : LifecycleService() {
    @Inject
    lateinit var weatherRepository: WeatherRepository

    @Inject
    lateinit var weatherService: WeatherService

    private var isRunning = false

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        super.onStartCommand(intent, flags, startId)

        if (!isRunning) {
            isRunning = true
            startPeriodicUpdates()
        }

        return START_STICKY
    }

    private fun startPeriodicUpdates() {
        lifecycleScope.launch {
            while (isRunning) {
                // 获取所有城市
                val cities = weatherRepository.getAllCities().value ?: emptyList()

                // 为每个城市更新天气
                for (city in cities) {
                    try {
                        weatherService.fetchAndSaveWeather(city)
                    } catch (e: Exception) {
                        e.printStackTrace()
                    }
                }

                // 每30分钟更新一次
                delay(30 * 60 * 1000)
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        isRunning = false
    }

    override fun onBind(intent: Intent): IBinder? {
        super.onBind(intent)
        return null
    }
}
